/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.cli;

import cz.mzk.oai.metadataRepository.metadata.MarcRecord;
import cz.mzk.oai.metadataRepository.metadata.MetadataFormat;
import cz.mzk.oai.metadataRepository.repository.AlephBase;
import cz.mzk.oai.metadataRepository.repository.Repository;
import cz.mzk.oai.metadataRepository.repository.collections.MarcBasedCollectionSelector;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.repository.records.Record;
import cz.mzk.oai.metadataRepository.repository.records.presentAndDeleted.PresentRecord;
import cz.mzk.rehan.commons.Dom4jUtils;
import java.io.IOException;
import java.util.List;
import org.dom4j.Document;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class PrintPossibleMovesAction extends Action {

    private final String collectionName;
    private final MarcBasedCollectionSelector selector;
    private final AlephBase alephBase;

    public PrintPossibleMovesAction(Repository repository, String collectionName, String alephBase) {
        super(repository);
        this.collectionName = collectionName;
        this.selector = new MarcBasedCollectionSelector(repository);
        this.alephBase = AlephBase.valueOf(alephBase);
    }

    @Override
    public void run() throws Exception {
        MetadataCollection collection = repository.findCollection(collectionName);
        if (collection == null) {
            throw new Exception("No such collection '" + collectionName + "'");
        }
        List<Record> records = collection.getRecords(MetadataFormat.marc21, null, null);
        CollectionsItemsMapping mapping = new CollectionsItemsMapping();
        int counter = 0;
        for (Record record : records) {
            String newCollection = findNewCollection(record);
            mapping.addItem(record.getId(), newCollection);
            if (++counter%10 == 0){
                System.gc();
            }
        }
        printItemsInCollections(mapping);
    }

    private String findNewCollection(Record record) throws IOException {
        if (!record.isDeleted()) {
            PresentRecord present = (PresentRecord) record;
            MarcRecord marcRecord = new MarcRecord(present.getMetadata());
            try {
                MetadataCollection collection = selector.chooseCollectionOrThrowException(marcRecord, alephBase);
                return collection.getName();
            } catch (Throwable ex) {
                return "SYSTEM:unknown";
            }
        }
        return "SYSTEM:deleted";
    }

    private void printItemsInCollections(CollectionsItemsMapping mapping) {
        System.out.println("printing");
        Document printDoc = mapping.asXml();
        Dom4jUtils.writeDocument(printDoc, System.out, Dom4jUtils.PrintType.PRETTY);
    }
}
